#include <mysql.h>
#include <stdio.h>
#include <glib.h>
#include <mysql.h>

#include "server.h"
#include "db.h"

#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif

#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif


int update_server(MYSQL *conn, const struct server *s)
{
	static time_t now = 0;
	if(!now)
		now = time(NULL);
	if(s->maxplayers > 0 /*&& s->dedicated > 0*/) {
		char sql[4096];
		char *qname = db_escape(conn, s->name);
		char *qos = db_escape(conn, s->os);
		char *qgd = db_escape(conn, s->gamedescription);
		MYSQL_RES *sth2 = NULL;
		int numplayers = MIN(64, s->numplayers);
		int realplayers = numplayers - MIN(numplayers, MAX(s->bots,0));
		//fprintf(stderr, "numplayers: %i/%i bots: %i realplayers: %i\n", s->numplayers, numplayers, s->bots, realplayers);
		snprintf(sql, sizeof(sql), "INSERT INTO server "
				"(ip, port, name, gametype, totalplayers, maxplayers, lastUpdate, game, dedicated, secure, os, avarage, gamedescription) "
				"VALUES "
				"('%s', %i, '%s', '%s', %i, %i, FROM_UNIXTIME(%li), '%s', %i, %i, '%s', %i, '%s')"
				" ON DUPLICATE KEY UPDATE name = '%s', gametype = '%s', totalplayers = totalplayers + %i, maxplayers=%i, updates = updates + 1, lastUpdate = FROM_UNIXTIME(%li), game='%s', dedicated=%i, secure=%i, os='%s', gamedescription='%s'",
				s->ip, s->port, qname, s->gametype, realplayers, s->maxplayers, now, s->game, s->dedicated, s->secure, qos, realplayers, qgd,
				qname, s->gametype, realplayers, s->maxplayers, now, s->game, s->dedicated, s->secure, qos, qgd
			);
		fprintf(stderr, "%s\n", sql);
		g_free(qname);
		g_free(qos);
		g_free(qgd);
		sth2 = db_doSql(conn, sql);
		if(sth2)
			mysql_free_result(sth2);
	} else {
		fprintf(stderr, "Ignoring server. %i/%i\n", s->maxplayers, s->dedicated);
	}
	return 0;
}
